import React from 'react'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Modal, Table, message, Input } from 'antd'
import style from './ArbitratorSelector.module.less'
import { decomporessListLicenseAndMobileAndBank } from '@src/assets/js/tool'
const { Search } = Input
// 获取表格字段配置
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '名册序号',
      dataIndex: 'serialno',
      key: 'serialno',
      align: 'center',
      width: 80
    },
    {
      title: '擅长专业',
      dataIndex: 'special',
      key: 'special',
      width: '30%'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: v => {
        return v ? '在聘' : '解聘'
      }
    },
    {
      title: '职业',
      dataIndex: 'occupation',
      key: 'occupation'
    }
  ]
}

class ArbitratorSelector extends Component {
  state = {
    list: [],
    loading: false,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    selectedRowKeys: [],
    selectedRow: null,
    searchText: ''
  }

  // 获取案件数据
  getTableData (form) {
    const { pagination, searchText } = this.state
    const { current, pageSize } = pagination
    const data = {
      current,
      page_size: pageSize
    }
    if (searchText) {
      data.condition = JSON.stringify([{ k: 'name', o: 'like', v: `%${searchText}%` }])
    }
    this.setState({ loading: true })
    this.$get('/api/xapc/arbitrator', data).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        decomporessListLicenseAndMobileAndBank(res.data.list)
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        }, () => {
          this.initSelectedRow()
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 根据选中值设置选中项
  initSelectedRow () {
    const { list, selectedRow, pagination } = this.state
    const { pageSize, current } = pagination
    const { selectedId } = this.props
    if (!selectedRow && selectedId) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].id === selectedId) {
          this.setState({
            selectedRowKeys: [i + 1 + pageSize * (current - 1)],
            selectedRow: list[i]
          })
          break
        }
      }
    }
  }

  // 表格请求变化
  tableChange ({ current, pageSize }) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 为禁用行设置样式
  getRowClass (record, index) {
    const { disableIds } = this.props
    if (disableIds.indexOf(record.id) !== -1) {
      return style['table-line-disable']
    }
  }

  // 重置数据
  resetData () {
    this.setState({
      list: [],
      selectedRowKeys: [],
      selectedRow: null,
      searchText: '',
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    })
  }

  // 点击确定按钮
  decideHandle () {
    if (!this.state.selectedRow && this.props.required) {
      return message.warning('请选择仲裁员')
    }
    this.props.onChange(this.state.selectedRow)
    this.props.hide()
  }

  // 搜索
  searchHandle (v) {
    this.setState({
      searchText: v,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  componentDidUpdate (prev) {
    if (this.props.visible !== prev.visible) {
      if (this.props.visible) {
        this.getTableData()
      } else {
        this.resetData()
      }
    }
  }

  componentDidMount () {
    this.getTableData()
  }

  render () {
    const { selectedRowKeys } = this.state
    const rowSelection = {
      type: 'radio',
      selectedRowKeys: selectedRowKeys,
      getCheckboxProps: record => ({ ...record, disabled: this.props.disableIds.indexOf(record.id) !== -1 }),
      onChange: (selectedRowKeys, selectedRows) => {
        const { disableIds } = this.props
        if (disableIds.indexOf(selectedRows[0].id) !== -1) {
          return false
        }
        this.setState({ selectedRowKeys, selectedRow: selectedRows[0] })
      }
    }
    const onRow = record => ({
      onClick: e => {
        const { disableIds } = this.props
        if (disableIds.indexOf(record.id) !== -1) {
          return false
        }
        const { pageSize, current } = this.state.pagination
        const index = this.state.list.indexOf(record) + (current - 1) * pageSize
        this.setState({ selectedRowKeys: [index + 1], selectedRow: record })
      }
    })
    return (
      <Modal
        title='仲裁员选择器'
        open={this.props.visible}
        width={800}
        onOk={() => this.decideHandle()}
        onCancel={() => this.props.hide()}
        maskClosable={false}
        destroyOnClose
      >
        <div className={style['search-line']}>
          <div className={style['search-input']}>
            <Search placeholder='请输入仲裁员名称' onSearch={v => this.searchHandle(v)} allowClear enterButton />
          </div>
        </div>
        <Table loading={this.state.loading} rowClassName={(...args) => this.getRowClass(...args)} onRow={onRow} rowSelection={rowSelection} columns={getColumns.call(this)} dataSource={this.state.list} pagination={this.state.pagination} onChange={v => this.tableChange(v)} />
      </Modal>
    )
  }
}

ArbitratorSelector.propTypes = {
  visible: PropTypes.bool,
  onChange: PropTypes.func,
  hide: PropTypes.func,
  disableIds: PropTypes.array,
  selectedId: PropTypes.string,
  required: PropTypes.bool
}
ArbitratorSelector.defaultProps = {
  visible: false,
  onChange: data => {},
  hide: data => {},
  disableIds: [],
  selectedId: undefined,
  required: false
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(ArbitratorSelector)
